//
//  ImagesBrowser.swift
//  zhengwutong
//
//  Created by Bernie on 16/8/31.
//  Copyright © 2016年 wangshuguan. All rights reserved.
//

import UIKit
import AlamofireImage
import JXPhotoBrowser
class ImagesBrowserController: UIViewController,UIScrollViewDelegate,UIAlertViewDelegate {
    class func showImages(images:[Any],index:Int,saveTitle:String = "是否保存图片到手机") {
        guard index < images.count else{
            ZWTPrint("error index")
            return
        }
        guard images.isNotEmpty else {
            ZWTPrint("image is empty,pls check")
            return
        }
        let browser = JXPhotoBrowser()
        browser.numberOfItems = {
            images.count
        }
        browser.reloadCellAtIndex = { context in
            let browserCell = context.cell as? JXPhotoBrowserImageCell
            let indexPath = IndexPath(item: context.index, section: 0)
            if let img = images[indexPath.item] as? UIImage {
                browserCell?.imageView.image = img
            }else if let img = images[indexPath.item] as? String,let url = URL(string: img.withHost) {
                browserCell?.imageView.af_setImage(withURL: url)
            }
            browserCell?.longPressedAction = {(cell, press) in
                if let img = cell.imageView.image {
                    UIAlertController.alertMessage(saveTitle, title: " ", btnTitles: ["保存","取消"]) { (index) in
                        if index == 0{
                            img.saveToPhotosAlbum()
                        }
                    }
                }
            }
        }
        browser.pageIndex = index
        browser.show()
    }
    
    fileprivate let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
    fileprivate let pageControl = UIPageControl()
    var removeAction:([String])->Void = {_ in}
    var imageUrls:[String] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if #available(iOS 13.0, *) {
            self.view.backgroundColor = .systemBackground
        } else {
            // Fallback on earlier versions
            self.view.backgroundColor = .white
        }
        self.edgesForExtendedLayout = []
        self.view.addSubview(pageControl)
        self.view.addSubview(scrollView)
    }
//    override func viewDidLayoutSubviews() {
//        super.viewDidLayoutSubviews()
//    }
    func initview() {
        UIApplication.shared.sendAction(#selector(resignFirstResponder), to: nil, from: nil, for: nil)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "删除", style: .plain, target: self, action: #selector(remove))
    }
    @objc func remove(){
        self.imageUrls.remove(at: self.pageControl.currentPage)
        removeAction(self.imageUrls)
        updateViews()
        if self.imageUrls.isEmpty {
            self.goBack()
        }
    }
    func showImageList(_ imglist:[String],delAction:@escaping (([String])->Void) = {_ in}) {
        self.title = "管理图片"
        initview()
        removeAction = delAction
        DispatchQueue.main.after(0.2) {[weak self] in
            if let SSelf = self{
                SSelf.pageControl.tintColor = .lightGray
                SSelf.pageControl.currentPageIndicatorTintColor = .darkGray
                SSelf.scrollView.frame = CGRect(x: 0, y: 0, width: SSelf.view.frame.size.width, height: SSelf.view.frame.size.height)
                SSelf.scrollView.delegate = self
                SSelf.scrollView.isPagingEnabled = true
                SSelf.scrollView.showsHorizontalScrollIndicator = false
                SSelf.pageControl.frame = CGRect(x: 0, y: SSelf.view.frame.size.height - 40, width: SSelf.view.frame.size.width, height: 40)
                SSelf.imageUrls = imglist
                SSelf.updateViews()
            }
        }
    }
    func updateViews() {
        scrollView.removeAllSubviews()
        scrollView.contentSize = CGSize(width: CGFloat(self.imageUrls.count)*UIScreen.main.width, height: self.scrollView.frame.size.height)
        var i = 0
        for item in imageUrls {
            let iv = UIImageView(frame:CGRect(x: CGFloat(i)*scrollView.et_width, y: 0, width: scrollView.et_width, height: scrollView.et_height))
            iv.contentMode = .scaleAspectFit
            if let url = URL(string: item.withHost){
                iv.af_setImage(withURL: url)
            }
            scrollView.addSubview(iv)
            i += 1
        }
        self.pageControl.numberOfPages = imageUrls.count
        self.pageControl.currentPage = 0
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let newPage = Int(scrollView.contentOffset.x/UIScreen.main.width)
        if newPage != pageControl.currentPage{
            pageControl.currentPage = min(newPage, pageControl.numberOfPages-1)
        }
    }
}
